package cn.bluech.lib.appbase;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlarmManager;
import android.app.Application;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;

import java.io.File;
import java.util.List;
import java.util.Stack;

import cn.bluech.lib.utils.AppUtils;
import cn.bluech.lib.utils.ListUtils;

/**
 * Description: 一些常用的功能统一处理
 * Create by Codeant on 2019/9/3.
 */
public class AppManager {
    private static final String CRASH_DIR = "crash";
    private static final String LOG_DIR   = "log";
    private static AppManager instance;

    private Application application;
    private String rootDir;
    private final Stack<Activity> activities = new Stack<>();


    public static AppManager getInstance() {
        if(null!=instance)
            return instance;
        synchronized (AppManager.class){
            if(null==instance)
                instance = new AppManager();
        }
        return instance;
    }

    private AppManager(){ }

    public void init(Application application, String dir, boolean isDebug, int logLevel){
        this.application = application;
        this.rootDir = dir;
        ExceptionCollector.getInstance()
                .init(application)
                .setListener(throwable -> exitApp());

        // Activity管理
        application.registerActivityLifecycleCallbacks(activityLifecycleCallbacks);

        if(!TextUtils.isEmpty(rootDir)){
            if(!rootDir.endsWith(File.separator))
                rootDir += File.separator;

            ExceptionCollector.getInstance().setStorageDir(rootDir+CRASH_DIR);
            // 日志文件
            ILog.setStorageDir(rootDir+LOG_DIR);
            ILog.setEnable(isDebug);
            ILog.setLog2FileLevel(logLevel);
        }
    }

    public void init(Application application){
        String rootDir = Environment.getExternalStorageDirectory().getAbsolutePath()
                + File.separator+ AppUtils.getName(application);

        init(application,rootDir,true, ILog.DISABLE);
    }

    public void restartApp(){
//        finishAllActivity();
//
//        Intent intent = new Intent(application, SplashActivity.class);
//        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//        application.startActivity(intent);
//        android.os.Process.killProcess(android.os.Process.myPid());

        // 1秒后重启
        finishAllActivity();

        Intent intent = application.getPackageManager()
                .getLaunchIntentForPackage(application.getPackageName());
        PendingIntent pendingIntent = PendingIntent.getActivity(application, 0, intent, PendingIntent.FLAG_ONE_SHOT);
        AlarmManager alarmManager = (AlarmManager)application.getSystemService(Context.ALARM_SERVICE);
        alarmManager.set(AlarmManager.RTC, System.currentTimeMillis() + 1000, pendingIntent); // 1秒钟后重启应用
        System.exit(0);
    }

    public void exitApp(){
        // 退出应用程序
        finishAllActivity();
        System.exit(0);
        android.os.Process.killProcess(android.os.Process.myPid());
    }

    /**
     * 是否在前台运行
     * Activity生命周期要走到onStop()这里才会时false
     */
    public boolean isForeground(){
        ActivityManager manager = (ActivityManager) application
                .getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> procs = manager.getRunningAppProcesses();
        if (ListUtils.isEmpty(procs))
            return false;

        for (ActivityManager.RunningAppProcessInfo proc : procs){
            if (proc.processName.equals(application.getPackageName())
              &&(proc.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND)){
                return true;
            }
        }

        return false;
    }

    public Activity getTopActivity(){
        try{
            return activities.peek();
        }catch (Exception ignored){
            return null;
        }
    }

    public void finishAllActivity(){
        synchronized (activities){
            while (!activities.isEmpty()){
                activities.pop().finish();
            }
        }
    }

    private Application.ActivityLifecycleCallbacks activityLifecycleCallbacks = new Application.ActivityLifecycleCallbacks() {
        @Override
        public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
            synchronized (activities){
                activities.add(activity); // activities.push(activity);
            }
        }

        @Override
        public void onActivityStarted(Activity activity) { }
        @Override
        public void onActivityResumed(Activity activity) { }
        @Override
        public void onActivityPaused(Activity activity) { }
        @Override
        public void onActivityStopped(Activity activity) { }
        @Override
        public void onActivitySaveInstanceState(Activity activity, Bundle outState) { }

        @Override
        public void onActivityDestroyed(Activity activity) {
            synchronized (activities){
                activities.remove(activity);
            }
        }
    };
}
